﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using System.Windows.Controls;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows;

namespace Helper_Ji
{
    public static class Helper_File
    {
        /// <summary>
        /// 保存控件--Control
        /// </summary>
        /// <param name="control"></param>
        public static void Save_Control(FrameworkElement control,int width,int height)
        {
            RenderTargetBitmap bmp = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);
            bmp.Render(control);
            string file = Save();
            if (file.Length == 0)
                return;
            string Extension = System.IO.Path.GetExtension(file).ToLower();
            BitmapEncoder encoder;
            if (Extension == ".gif")
                encoder = new GifBitmapEncoder();
            else if (Extension == ".png")
                encoder = new PngBitmapEncoder();
            else if (Extension == ".jpg")
                encoder = new JpegBitmapEncoder();
            else if (Extension == ".bmp")
                encoder = new BmpBitmapEncoder();
            else
                return;
            encoder.Frames.Add(BitmapFrame.Create(bmp));
            using (Stream stm = File.Create(file))
            {
                encoder.Save(stm);
            }
        }

        /// <summary>
        /// 保存图片--BitMap
        /// </summary>
        /// <param name="bitmap"></param>
        public static void SaveImageCapture(BitmapSource bitmap)
        {
            JpegBitmapEncoder encoder = new JpegBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bitmap));
            encoder.QualityLevel = 100;
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.FileName = "Image";
            dlg.DefaultExt = ".Jpg";
            dlg.Filter = "Image (.jpg)|*.jpg";
            Nullable<bool> result = dlg.ShowDialog();
            if (result == true)
            {
                string filename = dlg.FileName;
                FileStream fstream = new FileStream(filename, FileMode.Create);
                encoder.Save(fstream);
                fstream.Close();
            }
        }

        /// <summary>
        /// 打开文件--*.*
        /// </summary>
        /// <returns></returns>
        public static string Search()
        {
            string filPath = string.Empty;
            System.Windows.Forms.OpenFileDialog openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
            openFileDialog1.Filter = "文件(*.*)|*.*";
            openFileDialog1.FilterIndex = 0;
            openFileDialog1.RestoreDirectory = true;
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                filPath = openFileDialog1.FileName;
            }
            else
            { }
            return filPath;
        }

        /// <summary>
        /// 新建目录
        /// </summary>
        /// <param name="path"></param>
        /// <param name="directorySecurity"></param>
        /// <returns></returns>
        public static string CreatPath(string path, System.Security.AccessControl.DirectorySecurity directorySecurity)
        {
            try
            {
                if (directorySecurity == null)
                    Directory.CreateDirectory(path, directorySecurity);
                else Directory.CreateDirectory(path);
                return "true";
            }
            catch (InvalidCastException e) { return e.Message; }
        }

        /// <summary>
        /// 保存图片文件
        /// </summary>
        /// <returns></returns>
        public static string Save()
        {
            string filPath = string.Empty;
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.FileName = DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss");
            dlg.DefaultExt = ".jpg";
            dlg.Filter = "JPG|*.jpg" + "|PNG|*.png" + "|BMP|*.bmp" + "|GIF|*.gif";

            Nullable<bool> result = dlg.ShowDialog();
            if (result == true)
            {
                filPath = dlg.FileName;
            }
            return filPath;
        }

    }
    public class JiHelper_MemoryFile
    {
        [Serializable]
        public class MemoryFileClass
        {
            public object File;
        }
        public class MemoryFile
        {
            /// <summary>
            /// 内容
            /// </summary>
            public object FileTemp;
            private MemoryMappedFile memoryFile = null;
            private MemoryMappedViewStream stream = null;

            /// <summary>
            /// 最大容量
            /// </summary>
            private const int FileSize = 1024 * 1024;

            /// <summary>
            /// 创建内存映射文件,获取其读写流
            /// </summary>
            /// <param name="name">名称</param>
            /// <param name="value">大小 * 1M</param>
            /// <returns></returns>
            public bool InitMemoryMappedFile(string name, int value)
            {
                bool re = false;
                try
                {
                    memoryFile = MemoryMappedFile.CreateOrOpen(name, FileSize * value);
                    stream = memoryFile.CreateViewStream();
                    re = true;
                }
                catch
                {
                    re = false;
                }
                return re;
            }

            /// <summary>
            /// 将obj对象保存到内存映射文件中
            /// </summary>
            public string SaveToMMF(MemoryFileClass obj)
            {
                try
                {
                    IFormatter formatter = new BinaryFormatter();
                    stream.Seek(0, SeekOrigin.Begin);
                    formatter.Serialize(stream, obj);
                    return "true";
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }
            }

            /// <summary>
            /// 从内存中读取obj
            /// </summary>
            /// <returns></returns>
            public string LoadFromMMF()
            {
                try
                {
                    IFormatter formatter = new BinaryFormatter();
                    stream.Seek(0, SeekOrigin.Begin);
                    MemoryFileClass obj = formatter.Deserialize(stream) as MemoryFileClass;
                    if (obj != null)
                    {
                        FileTemp = obj.File;
                    }
                    return "true";
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }
            }

            /// <summary>
            /// 释放相关资源
            /// </summary>
            public void DisposeMemoryMappedFile()
            {
                if (stream != null)
                    stream.Close();
                if (memoryFile != null)
                    memoryFile.Dispose();
            }
        }
    }
}